<?php
declare (strict_types = 1);
namespace app\index\model\order;

use app\index\model\charge\ChargingStation;
use think\Model;

/**
 * @mixin \think\Model
 */
class PileOrder extends Model
{
    protected $pk = "id";

    /**
     * 获取信息
     * @param $where
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getInfoByWhere($where){
        return $this->where($where)->order('id','desc')->find();
    }

    /**
     * 获取信息
     * @param $id
     * @param $addWhere
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getInfoById($id,$addWhere = [],$field='*'){
        $where = ['id'=>$id,'is_del'=>0,'is_system_del'=>0];
        $info = $this->where($where)->where($addWhere)->field($field)->find();
        if($info){
            $statusName = config('index.order_status_name');
            $paidName = [0=>'未支付',1=>'已支付'];
            $payTypeName = config('index.pay_type_name');
            $info['status_name'] = isset($statusName[$info['status']]) ? $statusName[$info['status']] : "";
            $info['paid_name'] = isset($paidName[$info['paid']]) ? $paidName[$info['paid']] : "";
            if($info['paid'] == 0){
                $info['pay_type_name'] = '订单暂未支付';
            }else{
                $info['pay_type_name'] = isset($payTypeName[$info['pay_type']]) ? $payTypeName[$info['pay_type']] : '';
            }
        }
        return $info;
    }

    /**
     * 添加订单
     * @param $userInfo
     * @param $pileInfo
     * @param $gunInfo
     * @param $costInfo
     * @return array|bool
     */
    function addOrder($userInfo,$pileInfo,$gunInfo,$costInfo){
        $orderData = [
            'uid'=>$userInfo['id'],
            'spread_uid'=>$userInfo['spread_uid'],
            'order_sn'=>$this->getOrderNumber(),
            'pile_id'=>$pileInfo['id'],
            'station_id'=>$pileInfo['station_id'],
            'pile_gun_number'=>$gunInfo['num'],
            'gun_id'=>$gunInfo['id'],
            //'start_time'=>date("Y-m-d H:i:s"),
            'charge_cost'=>$pileInfo['charge_cost'],
            'service_cost'=>$pileInfo['service_cost'],
            'peak_electric_cost'=>$pileInfo['peak_electric_cost'],
            'peak_service_cost'=>$pileInfo['peak_service_cost'],
            'flat_electric_cost'=>$pileInfo['flat_electric_cost'],
            'flat_service_cost'=>$pileInfo['flat_service_cost'],
            'valley_electric_cost'=>$pileInfo['valley_electric_cost'],
            'valley_service_cost'=>$pileInfo['valley_service_cost'],
            'cost_id'=>$pileInfo['cost_id'],
            'cost_content'=>$costInfo['cost_value'],
            'paid'=>0,
            'status'=>0,
            'is_del'=>0,
            'is_system_del'=>0,
            'create_time'=>date("Y-m-d H:i:s"),         //创建时间
            'update_time'=>date("Y-m-d H:i:s"),         //修改建时间
            'battery_type'=>'',
            'start_type'=>4,
            'gun_markings'=>0,
        ];
        $orderId = $this->insertGetId($orderData);
        if($orderId){
            $orderData['id'] = $orderId;
            return $orderData;
        }else{
            return false;
        }
    }

    /**
     * 添加虚拟订单
     * @param $userInfo
     * @param $pileInfo
     * @param $gunInfo
     * @param $costInfo
     * @return array|bool
     */
    function addVirtuallyOrder($userInfo,$pileInfo,$gunInfo,$addData,$costInfo){
        $orderData = [
            'uid'=>$userInfo['id'],
            'spread_uid'=>$userInfo['spread_uid'],
            'order_sn'=>$this->getOrderNumber(),
            'pile_id'=>$pileInfo['id'],
            'station_id'=>$pileInfo['station_id'],
            'pile_gun_number'=>$gunInfo['num'],
            'gun_id'=>$gunInfo['id'],
            'start_time'=>$addData['start_time'],
            'charge_cost'=>$pileInfo['charge_cost'],
            'service_cost'=>$pileInfo['service_cost'],
            'peak_electric_cost'=>$pileInfo['peak_electric_cost'],
            'peak_service_cost'=>$pileInfo['peak_service_cost'],
            'flat_electric_cost'=>$pileInfo['flat_electric_cost'],
            'flat_service_cost'=>$pileInfo['flat_service_cost'],
            'valley_electric_cost'=>$pileInfo['valley_electric_cost'],
            'valley_service_cost'=>$pileInfo['valley_service_cost'],
            'cost_id'=>$pileInfo['cost_id'],
            'cost_content'=>$costInfo['cost_value'],
            'paid'=>0,
            'status'=>$addData['status'],
            'is_del'=>0,
            'is_system_del'=>0,
            'create_time'=>date("Y-m-d H:i:s"),         //创建时间
            'update_time'=>date("Y-m-d H:i:s"),         //修改建时间
            'battery_type'=>'',
            'start_type'=>4,
            'gun_markings'=>-1,
            'order_type'=>2,
        ];
        $orderId = $this->insertGetId($orderData);
        if($orderId){
            $orderData['id'] = $orderId;
            return $orderData;
        }else{
            return false;
        }
    }

    /**
     * 获取订单编号
     * @return string
     */
    function getOrderNumber(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $rand1 = mt_rand(10000, max(intval($msec * 10000) + 10000, 98369));
        $rand2 = mt_rand(10000, 99999);
        $orderSn = '100' . $msectime . mt_rand(10000, max(intval($msec * 10000) + 10000, 98369)).$rand1.$rand2;
        if(strlen($orderSn) > 32){
            $orderSn = substr($orderSn,0,32);
        }else if(strlen($orderSn) < 32){
            $orderSn = str_pad($orderSn,32,'0',STR_PAD_RIGHT);
        }
        return $orderSn;
    }

    /**
     * 未支付订单查询
     * @param $userId
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function checkOrder($userId){
        $where = ['uid'=>$userId,'is_del'=>0,'is_system_del'=>0,'paid'=>0];
        return $this->where($where)->whereIn('status','1,2,3')->find();
    }

    /**
     * 判断是否有充电中的订单
     * @param $userId
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function checkChargeOrder($userId){
        $where = ['uid'=>$userId,'is_del'=>0,'is_system_del'=>0,'paid'=>0,'status'=>1];
        return $this->where($where)->find();
    }

    /**
     * 更改订单
     * @param $orderId
     * @param $saveData
     * @return static
     */
    function updateOrder($orderId,$saveData){
        return $this->where('id',$orderId)->update($saveData);
    }

    /**
     * 获取用户订单列表
     * @param $userId
     * @param array $addWhere
     * @param int $page
     * @param int $limit
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getUserOrderList($userId,$addWhere = [],$page=1,$limit=15,$field="*"){
        $where = ['uid'=>$userId,'is_del'=>0,'is_system_del'=>0];
        $count =  $this->where($where)->where($addWhere)->count();
        $statusName = config('index.order_status_name');
        $paidName = [0=>'未支付',1=>'已支付'];
        $payTypeName = config('index.pay_type_name');
        $chargingStationModel = new ChargingStation();
        $list = $this->where($where)->where($addWhere)->page($page,$limit)->order('id','desc')->field($field)->select()
            ->each(function ($item) use($statusName,$paidName,$payTypeName,$chargingStationModel){
                $item['status_name'] = isset($statusName[$item['status']]) ? $statusName[$item['status']] : "";
                $item['paid_name'] = isset($paidName[$item['paid']]) ? $paidName[$item['paid']] : "";
                if($item['paid'] == 0){
                    $item['pay_type_name'] = '订单暂未支付';
                }else{
                    $item['pay_type_name'] = isset($payTypeName[$item['pay_type']]) ? $payTypeName[$item['pay_type']] : '';
                }
                if(isset($item['station_id'])){
                    $stationInfo = $chargingStationModel->getInfoById($item['station_id'],'id,title');
                    $item['station_name'] = isset($stationInfo['title']) ? $stationInfo['title'] : '';
                }
                return $item;
            })->toArray();
        return compact('count','list');
    }

    /**
     * 获取用户充电中的订单
     * @param $userId
     * @return array|null|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getUserChargeOrderInfo($userId){
        $where = ['uid'=>$userId,'is_del'=>0,'is_system_del'=>0,'status'=>1];
        $orderInfo = $this->where($where)->find();
        return $orderInfo;
    }

    /**
     * 获取指定的的订单
     * @param $where
     * @param int $page
     * @param int $limit
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getOrderListByWhere($where,$page = 1,$limit = 10,$field="*"){
        $count = $this->where($where)->count();
        $list = $this->where($where)->page($page,$limit)->field($field)
            ->order('id','desc')->select();
        if($list) $list->toArray();
        return compact('count','list');
    }

}
